<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Api;

use App\Model\YellowPage;
use App\Resource\YellowPageCollection;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;

#[Controller]
class YellowPageController
{
    #[Inject]
    protected RequestInterface $request;


    #[RequestMapping(path: "", methods: "get")]
    /**
     * 列表
     * @return false|string
     */
    public function list()
    {
        $list = YellowPage::query();
        $list->active();
        if ($keyword = $this->request->input('keyword')) {
            $list->keyword($keyword);
        }

        $list = $list->paginate((integer)$this->request->input('page_num', 15));

        $data = [
            'list' => (new YellowPageCollection($list))->toListApi(),
            'count' => $list->total(),
            'count_page' => $list->lastPage(),
            'page_num' => $list->perPage(),
        ];
        return self::jsonResponse(200, 'success', $data);
    }


    /**
     * 返回统一json
     * @param int $status
     * @param $message
     * @param $data
     * @param $headerStatus
     * @return false|string
     */
    public static function jsonResponse(int $status = 1, $message = 'success', $data = null, $headerStatus = 200)
    {
        if (is_array($message)) {
            $data = $message;
            $message = 'success';
        }
        if (empty($data)) {
            $data = new class {
            };
        }

        return json_encode(['status' => $status, 'message' => $message, 'data' => $data]);

//        return response()->json(
//            ['status' => $status, 'message' => $message, 'data' => $data],
//            $headerStatus,
//            [],
//            JSON_UNESCAPED_UNICODE
//        );
    }
}
